from rest_framework.views import APIView
from rest_framework.response import Response
from .serialzer import *


class GradeAPIView(APIView):
    def post(self, request):
        name = request.data.get('name')
        grade_obj = Grade.objects.filter(name=name)
        if grade_obj:
            return Response({'msg': '该班级已保存', 'code': 400})
        else:
            grade_serializer = GradeModelSerializer(data=request.data)
        if grade_serializer.is_valid():
            grade_serializer.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            return Response(grade_serializer.errors)

    def get(self, request):
        grade_list = Grade.objects.all()
        grade_serializer = GradeModelSerializer(grade_list, many=True)
        return Response(grade_serializer.data)


class StudentAPIView(APIView):
    def post(self, request):
        name = request.data.get('name')
        student_obj = Grade.objects.filter(name=name)
        if student_obj:
            return Response({'msg': '该学生已保存', 'code': 400})
        else:
            student_serializer = StudentModelSerializer(data=request.data)
        if student_serializer.is_valid():
            student_serializer.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            return Response(student_serializer.errors)

    def get(self, request):
        grade_id = request.GET.get('grade_id')
        student_list = Student.objects.filter(grade_id=grade_id)
        student_serializer = StudentModelSerializer(student_list, many=True)
        return Response(student_serializer.data)


class StudentDetailAPIView(APIView):
    def get(self, request):
        student_id = request.query_params.get('student_id')
        try:
            student_list = Student.objects.filter(pk=student_id)
        except Student.DoesNotExist:
            return Response({'msg': '信息有误', 'code': 400})
        else:
            student_serializer = ShowStudentModelSerializer(student_list,many=True)
            return Response(student_serializer.data)
